package org.pmt.first.kms.screen

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import com.dream.common.currentPlatform
import io.github.aakira.napier.Napier
import kotlinx.coroutines.flow.Flow
import moe.tlaster.precompose.molecule.collectAction
import moe.tlaster.precompose.molecule.rememberPresenter
import org.jetbrains.compose.ui.tooling.preview.Preview
import org.koin.compose.koinInject
import org.pmt.first.kms.data.entity.NewsHotItem
import org.pmt.first.kms.data.network.OnlineRepository
import org.pmt.first.resource.NavRoutes


@Composable
@Preview
fun HomeNewScreen(navController: NavHostController) {
    val (state, channel) = rememberPresenter { HomePresenter(it) }
    channel.trySend(HomeAction.Init)
    MaterialTheme {
        Scaffold {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
            ) {
                val newsList = state.newsList
                items(newsList.size) {
                    newsList.forEach {
                        NewsHotItem(it) {
                            navController.navigate(NavRoutes.SETTING("123"))
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun HomePresenter(
    action: Flow<HomeAction>,
): HomeState {
    var newsList by remember { mutableStateOf(mutableListOf<NewsHotItem>()) }
    val onlineRepository: OnlineRepository = koinInject()

    action.collectAction {
        when (this) {
            HomeAction.Init -> {
//                val result = onlineRepository.getNewsHot()
//                when (result) {
//                    is Either.Left<HttpError> -> {
//
//                    }
//                    is Either.Right<NewsHotResponse> -> {
//                        newsList = result.value.result.list.toMutableList()
//                    }
//                }
                Napier.d("teng  ${currentPlatform().name} ${currentPlatform().arch}")
            }
            HomeAction.LoadMore -> TODO()
        }
    }
    return HomeState(newsList)
}

sealed interface HomeAction {
    data object Init : HomeAction
    data object LoadMore : HomeAction
}

data class HomeState(
    val newsList: List<NewsHotItem>,
)